package com.partners.service.Impl;

import com.partners.configure.wechatmp.WxMpConfiguration;
import com.partners.constant.BusinessMessage;
import com.partners.constant.ErrorMessageEnum;
import com.partners.model.BusinessException;
import com.partners.service.AuthService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liangyongle
 * @date 2018-12-13
 */
@Service
public class AuthServiceImpl implements AuthService {
    public final static String appId = "wx1b38cf3729aaa2a7";

    /**
    * 生成二维码
    * param type Integer uid Integer customerId Integer
    * return qrcodeUrl String
    * */
    @Override
    public String getMpCode(Integer type, Integer uid, Integer customerId) {
        final WxMpService wxService = WxMpConfiguration.getMpServices().get(appId);
        String accessToken = "";
        try {
             accessToken  = wxService.getAccessToken();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String sceneStr = "type="+type+"&uid="+uid;
        if(type == 2){
            sceneStr = "type="+type+"&uid="+uid+"&customerId="+customerId;
        }
        Integer expireSeconds = 604800;
        Map<String,Object> data = new HashMap<>();
        String showUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
        try {
            WxMpQrCodeTicket wxMpQrCodeTicket = wxService.getQrcodeService().qrCodeCreateTmpTicket(sceneStr,expireSeconds);
            if(wxMpQrCodeTicket != null){
                String ticket = wxMpQrCodeTicket.getTicket();
                return showUrl+ticket;
            }else{
                throw BusinessException.of(ErrorMessageEnum.QRCODE_ERROR);
            }
        } catch (WxErrorException e) {
            throw BusinessException.of(new BusinessMessage() {
                @Override
                public Integer getCode() {
                    return -10002;
                }

                @Override
                public String getMsg() {
                    return e.getMessage().toString();
                }
            });

        }
    }
}
